package com.zbkj.crmeb.chant.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.CommonPage;
import com.common.PageParamRequest;
import com.crmeb.core.common.CommonResult;
import com.crmeb.core.config.MybatisPlusConfig;
import com.crmeb.core.exception.CrmebException;
import com.crmeb.core.utils.TableNameUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.utils.DateUtil;
import com.utils.PriceUtil;
import com.utils.ProductConvertUtil;
import com.zbkj.crmeb.chant.dao.ChannelActivityDao;
import com.zbkj.crmeb.chant.model.CategoryMatch;
import com.zbkj.crmeb.chant.model.ChannelActivity;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.request.ActivityDetailsRequest;
import com.zbkj.crmeb.chant.request.ActivityListRequest;
import com.zbkj.crmeb.chant.request.ActivityProductsRequest;
import com.zbkj.crmeb.chant.request.AddActivityRequest;
import com.zbkj.crmeb.chant.service.ChannelActivityService;
import com.zbkj.crmeb.chant.service.ICategoryMatchService;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.enums.AreaTypeEnum;
import com.zbkj.crmeb.store.dao.StoreProductActivityDao;
import com.zbkj.crmeb.store.model.StoreProduct;
import com.zbkj.crmeb.store.model.StoreProductActivity;
import com.zbkj.crmeb.store.model.StoreProductAttrValue;
import com.zbkj.crmeb.store.model.StoreProductMer;
import com.zbkj.crmeb.store.model.Supplier;
import com.zbkj.crmeb.store.response.StoreProductAttrValueResponse;
import com.zbkj.crmeb.store.response.StoreProductResponse;
import com.zbkj.crmeb.store.service.StoreProductActivityService;
import com.zbkj.crmeb.store.service.StoreProductAttrValueService;
import com.zbkj.crmeb.store.service.StoreProductMerService;
import com.zbkj.crmeb.store.service.StoreProductService;
import com.zbkj.crmeb.store.service.SupplierService;

/**
 * <p>
 * 商户限时活动表 服务实现类
 * </p>
 *
 * @author wuzp
 * @since 2022-05-30
 */
@Service
public class ChannelActivityServiceImpl extends ServiceImpl<ChannelActivityDao, ChannelActivity> implements ChannelActivityService {

    @Resource
    private ChannelActivityDao channelActivityDao;
    @Resource
    private StoreProductActivityDao storeProductActivityDao;
    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private ICategoryMatchService categoryMatchService;
    @Autowired
    private PriceUtil priceUtil;
    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    private ProductConvertUtil productConvertUtil;
    @Autowired
    private StoreProductMerService storeProductMerService;
    @Autowired
    private StoreProductActivityService storeProductActivityService;
    @Autowired
    private StoreProductService storeProductService;

    @Override
    public CommonResult<String> addActivity(AddActivityRequest request) {
        if(request.getLimitTotal() > 0 && request.getLimited() == null){
            throw new CrmebException("超出限购状态不能为空");
        }
        if(request.getStartTime().before(new Date())){
            throw new CrmebException("活动开始时间必须大于当前时间");
        }
        if(request.getPreheating() != 3){
            if(request.getPreheating() == 1){
                request.setPreheatingStartTime(new Date());
                request.setPreheatingEndTime(DateUtil.addSecond(request.getStartTime(),-1));
            }else if(request.getPreheating() == 2) {
               if(request.getPreheatingStartTime() == null || request.getPreheatingEndTime() == null){
                    throw new CrmebException("预热时间不能为空");
                }
               if(request.getPreheatingEndTime().after(request.getStartTime())){
                   throw new CrmebException("预热时间不能超过活动开始时间");
               }
            }
            if(request.getPreheatingBuy() == null){
                throw new CrmebException("预热期间是否购买不能为空");
            }
        }
        List<String> imageList = JSONObject.parseArray(request.getImage(), String.class);
        if (imageList.size() > 9) {
            throw new CrmebException("banner图最多上传9张");
        }
        ChannelActivity channelActivity = new ChannelActivity();
        BeanUtils.copyProperties(request,channelActivity);
        return this.save(channelActivity) ? CommonResult.success() : CommonResult.failed();
    }

    @Override
    public PageInfo<ChannelActivity> getMerActivityList(ActivityListRequest request, Integer merId) {
        LambdaQueryWrapper<ChannelActivity> lambdaQueryWrapper = Wrappers.<ChannelActivity>lambdaQuery()
                .eq(ChannelActivity::getMerId, merId)
                .eq(ChannelActivity::getIsDel, 0)
                .orderByDesc(ChannelActivity::getId);
        if(StringUtils.isNotBlank(request.getName())){
            lambdaQueryWrapper.like(ChannelActivity::getName,request.getName());
        }
        if(StringUtils.isNotBlank(request.getMark())){
            lambdaQueryWrapper.like(ChannelActivity::getMark,request.getMark());
        }
        if(request.getCrowd() != null){
            lambdaQueryWrapper.eq(ChannelActivity::getCrowd,request.getCrowd());
        }
        Page<ChannelActivity> page = PageHelper.startPage(request.getPage(), request.getLimit());
        List<ChannelActivity> list = this.list(lambdaQueryWrapper);
        return CommonPage.copyPageInfo(page, list);
    }

    @Override
    public CommonResult<String> deleteActivity(Integer id, Integer merId) {
        //判断能否删除
        ChannelActivity activity = this.getById(id);
        if(activity == null || activity.getIsDel() == 1){
            throw new CrmebException("该活动不存在");
        }
        /*if(activity.getStartTime().before(new Date()) && activity.getEndTime().after(new Date())){
            throw new CrmebException("正在进行中的活动不能删除");
        }*/
        activity.setIsDel(1);
        return this.updateById(activity) ? CommonResult.success() : CommonResult.failed();
    }

    @Override
    public PageInfo<StoreProductResponse> getProducts(ActivityProductsRequest request) {
        ChannelActivity activity = this.getById(request.getActivityId());
        if(activity == null || activity.getIsDel() == 1){
            throw new CrmebException("该活动不存在");
        }
        getProductConfig(request);
        Page<StoreProduct> page = PageHelper.startPage(request.getPage(), request.getLimit());
        List<StoreProduct> storeProducts = storeProductActivityDao.selectActivityProducts(request);
        if(CollectionUtils.isEmpty(storeProducts)) {
            return CommonPage.copyPageInfo(page, new ArrayList<>());
        }
        // 匹配详情属性
        productConvertUtil.convertProduct(storeProducts);
        //查询加价率
        List<Integer> ids = storeProducts.stream().map(StoreProduct::getId).collect(Collectors.toList());
        Map<Integer, StoreProductMer> storeProductMerMap = priceUtil.calcProductPrice(storeProducts, request.getMerId(), AreaTypeEnum.CN.getType());
        // 处理attrValue数据
        List<StoreProductAttrValue> attrValues = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery().in(StoreProductAttrValue::getProductId, ids));
        Map<Integer, List<StoreProductAttrValue>> attrValueMap = attrValues.stream().collect(Collectors.groupingBy(StoreProductAttrValue::getProductId));
        // 循环赋值
        List<StoreProductResponse> storeProductResponses = new ArrayList<>();
        for(StoreProduct product : storeProducts) {
            Integer id = product.getId();
            // 对象复制
            StoreProductResponse storeProductResponse = new StoreProductResponse();
            BeanUtils.copyProperties(product, storeProductResponse);
            List<StoreProductAttrValue> values = attrValueMap.get(id);
            // 查询对应属性赋值
            if(values==null){
                continue;
            }
            priceUtil.calcProductValuePrice(values,  request.getMerId(), product, AreaTypeEnum.CN.getType(), storeProductMerMap,false, null,true,null);
            //计算秒杀价
            priceUtil.calcSpikePrice(values,request.getActivityId(), request.getMerId());
//            List<StoreProductAttrValue> values = attrValueMap.get(id);
            List<StoreProductAttrValueResponse> valueResponses = new ArrayList<>();
            BigDecimal minSpikePrice = values.get(0).getSpikePrice();
            for(StoreProductAttrValue value : values) {
                StoreProductAttrValueResponse valueResponse = new StoreProductAttrValueResponse();
                BeanUtils.copyProperties(value, valueResponse);
                valueResponses.add(valueResponse);
                if(value.getSpikePrice().compareTo(minSpikePrice) < 0){
                    minSpikePrice = value.getSpikePrice();
                }
            }
            storeProductResponse.setSpikePrice(minSpikePrice);
            storeProductResponse.setAttrValue(valueResponses);
            storeProductResponses.add(storeProductResponse);
        }
        return CommonPage.copyPageInfo(page, storeProductResponses);
    }

    @Override
    public PageInfo<StoreProductResponse> getHomeProducts(ActivityProductsRequest request) {
        ChannelActivity activity = this.getById(request.getActivityId());
        if(activity == null || activity.getIsDel() == 1){
            throw new CrmebException("该活动不存在");
        }
        getProductConfig(request);
        Page<StoreProduct> page = PageHelper.startPage(request.getPage(), request.getLimit());
        List<StoreProduct> storeProducts = storeProductActivityDao.selectActivityProducts(request);
        if(CollectionUtils.isEmpty(storeProducts)) {
            return CommonPage.copyPageInfo(page, new ArrayList<>());
        }
        // 匹配详情属性
        productConvertUtil.convertProduct(storeProducts);
        List<StoreProductResponse> storeProductResponses = new ArrayList<>();
        for(StoreProduct product : storeProducts) {
            // 对象复制
            StoreProductResponse storeProductResponse = new StoreProductResponse();
            BeanUtils.copyProperties(product, storeProductResponse);
            storeProductResponses.add(storeProductResponse);
        }
        return CommonPage.copyPageInfo(page, storeProductResponses);
    }

    @Override
    public List<ChannelActivity> getMerActivityDropList(Integer type, Integer merId) {
        LambdaQueryWrapper<ChannelActivity> lambdaQueryWrapper = Wrappers.<ChannelActivity>lambdaQuery().eq(ChannelActivity::getIsDel, 0)
                .eq(ChannelActivity::getMerId, merId).select(ChannelActivity::getId, ChannelActivity::getName,ChannelActivity::getEndTime);
        if(type == 1){
            lambdaQueryWrapper.gt(ChannelActivity::getStartTime,new Date());
        }
        if(type == 2){
            lambdaQueryWrapper.gt(ChannelActivity::getEndTime,new Date());
        }
        return this.list(lambdaQueryWrapper);
    }

    @Override
    public PageInfo<StoreProductResponse> selectActivityProductList(ChannelActivity channelActivity, PageParamRequest pageParamRequest, Integer merId) {
        ActivityProductsRequest request = new ActivityProductsRequest();
        request.setActivityId(channelActivity.getId());
        request.setMerId(merId);
        request.setPage(pageParamRequest.getPage());
        request.setLimit(pageParamRequest.getLimit());
        return getProducts(request);
    }

    @Override
    public List<ChannelActivity> getActivityByProduct(ActivityDetailsRequest detailsRequest) {
        return channelActivityDao.getActivityByProduct(detailsRequest);
    }

    @Override
    public List<ChannelActivity> getActivityBySkuId(ActivityDetailsRequest detailsRequest) {
        return channelActivityDao.getActivityBySkuId(detailsRequest);
    }

    @Override
    public void limitedTimeEventProductOff() {
        //查询前一天是商户否有结束活动
//        LocalDate date = LocalDate.now().minusDays(1);
        List<ChannelActivity> channelActivityList = this.list(Wrappers.lambdaQuery(ChannelActivity.class)
                .eq(ChannelActivity::getProductStatus,1)
                .eq(ChannelActivity::getIsDel,0)
                .eq(ChannelActivity::getIsTask,0)
                .lt(ChannelActivity::getEndTime,new Date()));
//                .ge(ChannelActivity::getEndTime,LocalDateTime.of(date, LocalTime.MIN))
//                .le(ChannelActivity::getEndTime,LocalDateTime.of(date, LocalTime.MAX).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)));
        if (CollectionUtils.isNotEmpty(channelActivityList)){
            Map<Integer, List<ChannelActivity>> activityByMerIdMap = channelActivityList.stream().collect(Collectors.groupingBy(ChannelActivity::getMerId));
            for (Map.Entry<Integer, List<ChannelActivity>> entry : activityByMerIdMap.entrySet()) {
                Integer merId = entry.getKey();
                List<ChannelActivity> channelActivities = entry.getValue();
                List<Integer> activityIdList = channelActivities.stream().map(ChannelActivity::getId).collect(Collectors.toList());

                List<StoreProductActivity> productActivityList = storeProductActivityService.list(Wrappers.<StoreProductActivity>lambdaQuery()
                        .in(StoreProductActivity::getActivityId, activityIdList)
                        .select(StoreProductActivity::getProductId)
                        .groupBy(StoreProductActivity::getProductId));
                if(CollectionUtils.isNotEmpty(productActivityList)){
                    List<Integer> productIdList = productActivityList.stream().map(StoreProductActivity::getProductId).collect(Collectors.toList());
                    List<StoreProduct> productList = storeProductService.list(Wrappers.<StoreProduct>lambdaQuery()
                            .in(StoreProduct::getId, productIdList)
                            .select(StoreProduct::getId, StoreProduct::getMerId));
                    List<StoreProduct> insideProductList = productList.stream().filter(e -> Objects.equals(e.getMerId(), merId)).collect(Collectors.toList());
                    if(CollectionUtils.isNotEmpty(insideProductList)){
                        //自建修改主表  子表
                        List<Integer> insideProductIdList = insideProductList.stream().map(StoreProduct::getId).collect(Collectors.toList());
                        storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate().set(StoreProduct::getIsShow,0).in(StoreProduct::getId,insideProductIdList));
                        setStoreMerProductList(merId, insideProductIdList);
                    }
                    List<StoreProduct> cloudProductList = productList.stream().filter(e -> !Objects.equals(e.getMerId(), entry.getKey())).collect(Collectors.toList());
                    if(CollectionUtils.isNotEmpty(cloudProductList)){
                        List<Integer> cloudProductIdList = cloudProductList.stream().map(StoreProduct::getId).collect(Collectors.toList());
                        setStoreMerProductList(merId, cloudProductIdList);
                    }
                    this.update(Wrappers.<ChannelActivity>lambdaUpdate().set(ChannelActivity::getIsTask,1).in(ChannelActivity::getId,activityIdList));
                }
            }

//            List<Integer> activityIdList = channelActivityList.stream().map(ChannelActivity::getId).collect(Collectors.toList());
//            //查询活动对应的商品
//            List<StoreProductActivity> productActivityList = storeProductActivityService.list(Wrappers.lambdaQuery(StoreProductActivity.class)
//                    .in(StoreProductActivity::getActivityId,activityIdList)
//                    .select(StoreProductActivity::getActivityId,StoreProductActivity::getProductId)
//                    .groupBy(StoreProductActivity::getActivityId,StoreProductActivity::getProductId));
//            Map<Integer,List<StoreProductActivity>> productActivityMap = productActivityList.stream().collect(Collectors.groupingBy(StoreProductActivity::getActivityId));
//
//            Map<Integer,List<ChannelActivity>> map = channelActivityList.stream().collect(Collectors.groupingBy(ChannelActivity::getMerId));
//            map.forEach((key,value) ->{
//                List<Integer> productList = new ArrayList<>();
//                List<Integer> finalProductList = productList;
//                value.forEach(channelActivity -> {
//                    if (Objects.nonNull(productActivityMap.get(channelActivity.getId()))){
//                        List<Integer> integerList = productActivityMap.get(channelActivity.getId()).stream().map(StoreProductActivity::getProductId).collect(Collectors.toList());
//                        finalProductList.addAll(integerList);
//                    }
//                });
//                if (CollectionUtils.isNotEmpty(productList)){
//                    productList = productList.stream().distinct().collect(Collectors.toList());
//                    //查询商品是否存在
//                    //storeProductMerService.updateById()
//                }
//
//            });
        }
    }

    private void setStoreMerProductList(Integer merId,List<Integer> insideProductIdList) {
        for (Integer productId : insideProductIdList) {
            try {
                MybatisPlusConfig.tableNameMp.set(TableNameUtil.getProductMerName(merId));
                StoreProductMer storeMerProduct = storeProductMerService.getOne(Wrappers.<StoreProductMer>lambdaQuery().eq(StoreProductMer::getProductId, productId).last("LIMIT 1"));
                if(null == storeMerProduct) {
                    storeMerProduct = new StoreProductMer();
                    storeMerProduct.setProductId(productId);
                    storeMerProduct.setIsNotShow("1");
                    storeMerProduct.setIsSystemOut(0);
                    storeMerProduct.setCreateTime(new Date());
                    storeMerProduct.setUpdateTime(new Date());
                    MybatisPlusConfig.tableNameMp.set(TableNameUtil.getProductMerName(merId));
                    storeProductMerService.save(storeMerProduct);
                } else {
                    storeMerProduct.setIsNotShow("1");
                    storeMerProduct.setIsSystemOut(0);
                    storeMerProduct.setUpdateTime(new Date());
                    MybatisPlusConfig.tableNameMp.set(TableNameUtil.getProductMerName(merId));
                    storeProductMerService.updateById(storeMerProduct);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    private void getProductConfig(ActivityProductsRequest request) {
        ChannelMerchant channelMerchant = channelMerchantService.getChannelMerchantByMerId(request.getMerId());
        //可见配置
        List<Integer> brandIdsList = JSON.parseArray(channelMerchant.getBrandIds(), Integer.class);
        List<Integer> suppliersIdList = JSON.parseArray(channelMerchant.getSuppliersIds(), Integer.class);
        List<Integer> tempIdList = JSON.parseArray(channelMerchant.getTempId(), Integer.class);
        request.setVisibleBrandIds(brandIdsList);
        request.setVisibleTempIds(tempIdList);
        if (CollectionUtils.isNotEmpty(suppliersIdList)) {
            Supplier supplier = supplierService.getSupplierBarcode(request.getMerId());
            if (null != supplier) {
                suppliersIdList.add(supplier.getId());
            }
        }
        request.setVisibleSupplierIds(suppliersIdList);
        //不可见分类
        List<Integer> cateIdList = categoryMatchService.selectCategoryMatchDisable(request.getMerId()).stream().map(CategoryMatch::getId).collect(Collectors.toList());
        request.setInvisibleCateIds(cateIdList);
    }


}
